package a04_字符串;

import java.util.Arrays;


/**
 * <p>
 * a04_反转字符串中的单词
 * </p>
 *
 * @author flyduck
 * @since 2024-07-10
 */
public class a04_反转字符串中的单词复习3 {

    public static void main(String[] args) {
        System.out.println(reverseWords(" a good  sample  "));
    }

    public static String reverseWords(String oldStr) {
        char[] oldChars = oldStr.toCharArray();
        char[] newChars = removeAllSpaces(oldChars);
        reverse(newChars,0,newChars.length - 1);
        reverseEachWord(newChars);
        return new String(newChars);
    }

    //elpmas doog a
    private static void reverseEachWord(char[] chars) {
        int leftIdx = 0;
        int rightIdx = 0;
        while (rightIdx < chars.length) {
            if(rightIdx == chars.length - 1 || chars[rightIdx + 1] == ' '){
                reverse(chars, leftIdx, rightIdx);
                leftIdx = rightIdx + 2;
                rightIdx = leftIdx;
            }else {
                rightIdx++;
            }
        }
    }

    private static void reverse(char[] newChars, int leftIdx, int rightIdx) {
        while (leftIdx < rightIdx){
            char temp = newChars[leftIdx];
            newChars[leftIdx] = newChars[rightIdx];
            newChars[rightIdx] = temp;
            leftIdx++;
            rightIdx--;
        }
    }

    private static char[] removeAllSpaces(char[] oldChars) {
        int slowIdx = 0;
        int fastIdx = 0;
        while (fastIdx < oldChars.length){
            if(oldChars[fastIdx] != ' '){
                if (slowIdx != 0) {
                    oldChars[slowIdx] = ' ';
                    slowIdx++;
                }
                while (fastIdx < oldChars.length && oldChars[fastIdx] != ' ') {
                    oldChars[slowIdx] = oldChars[fastIdx];
                    fastIdx++;
                    slowIdx++;
                }
            }else {
                fastIdx++;
            }
        }
        return Arrays.copyOfRange(oldChars, 0, slowIdx);
    }


}
